import type { AppConfig, JobStatus, UserInfo } from '@shared/types/'
// 应用状态管理
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态
  const config = ref<AppConfig | null>(null)
  const currentUser = ref<UserInfo | null>(null)
  const jobs = ref<JobStatus[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 自动化页面持久化状态（交给 pinia-plugin-persistedstate）
  const automationSelectedIds = ref<number[]>([])
  const automationOptions = ref<any>({ headless: false, forceSelection: false, forceDate: '', forceTime: '' })
  const automationIsRunning = ref<boolean>(false)

  // 计算属性
  const hasConfig = computed(() => config.value !== null)
  const hasCurrentUser = computed(() => currentUser.value !== null)
  const runningJobs = computed(() => jobs.value.filter(job => job.status === 'running'))
  const completedJobs = computed(() => jobs.value.filter(job => ['success', 'failed', 'cancelled'].includes(job.status)))

  const loadConfig = async () => {
    try {
      const result = await window.api.config.get({})
      if (result.success) {
        config.value = result.config as AppConfig
      }
      else {
        throw new Error(result.error || '加载配置失败')
      }
    }
    catch (err) {
      console.error('加载配置失败:', err)
      throw err
    }
  }

  const loadJobs = async () => {
    try {
      const result = await window.api.script.status({})
      if (result.success) {
        jobs.value = result.jobs
      }
    }
    catch (err) {
      console.error('加载任务状态失败:', err)
    }
  }

  const initialize = async () => {
    try {
      isLoading.value = true
      error.value = null

      // 若配置尚未加载，则加载配置；否则跳过
      if (!config.value) {
        await loadConfig()
      }

      // 加载任务状态
      await loadJobs()

      console.log('✅ 应用状态初始化完成')
    }
    catch (err) {
      error.value = err instanceof Error ? err.message : '初始化失败'
      console.error('❌ 应用状态初始化失败:', err)
    }
    finally {
      isLoading.value = false
    }
  }

  const updateConfig = async (updates: Partial<AppConfig>) => {
    try {
      const result = await window.api.config.set({ config: updates })
      if (result.success) {
        // 重新加载配置
        await loadConfig()
        return true
      }
      else {
        const details = Array.isArray((result as any)?.validation_errors)
          ? `: ${(result as any).validation_errors.join('; ')}`
          : (result as any)?.message
              ? `: ${(result as any).message}`
              : ''
        throw new Error((result as any)?.error || `更新配置失败${details || ''}`)
      }
    }
    catch (err) {
      console.error('更新配置失败:', err)
      throw err
    }
  }

  const runScript = async (userInfo: UserInfo, options?: any) => {
    try {
      // 仅传递可克隆的纯对象
      const payload = JSON.parse(JSON.stringify({
        user_info: userInfo,
        mode: 'standard',
        options: options || {},
      }))
      const result = await window.api.script.run(payload)

      if (result.success) {
        // 刷新任务列表
        await loadJobs()
        return result.job_id
      }
      else {
        throw new Error(result.error || result.message)
      }
    }
    catch (err) {
      console.error('启动脚本失败:', err)
      throw err
    }
  }

  const stopScript = async (jobId: string) => {
    try {
      const result = await window.api.script.stop({ job_id: jobId })
      if (result.success) {
        // 刷新任务列表
        await loadJobs()
        return true
      }
      else {
        throw new Error(result.message)
      }
    }
    catch (err) {
      console.error('停止脚本失败:', err)
      throw err
    }
  }

  const clearHistory = async (options?: { keep_running?: boolean, older_than?: number }) => {
    try {
      const result = await (window as any).api.script.clear({
        keep_running: options?.keep_running ?? true,
        older_than: options?.older_than,
      })
      if (result.success) {
        await loadJobs()
        return result.deleted_count
      }
      else {
        throw new Error(result.error || '清空历史失败')
      }
    }
    catch (err) {
      console.error('清空历史失败:', err)
      throw err
    }
  }

  const setCurrentUser = (user: UserInfo) => {
    currentUser.value = user
  }

  const loadCurrentUser = () => {}

  const clearCurrentUser = () => {
    currentUser.value = null
  }

  const clearError = () => {
    error.value = null
  }

  // 初始化时加载用户信息（已持久化，无需额外处理）

  return {
    // 状态
    config,
    currentUser,
    jobs,
    isLoading,
    error,
    automationSelectedIds,
    automationOptions,
    automationIsRunning,

    // 计算属性
    hasConfig,
    hasCurrentUser,
    runningJobs,
    completedJobs,

    // 方法
    initialize,
    loadConfig,
    updateConfig,
    loadJobs,
    runScript,
    stopScript,
    clearHistory,
    setCurrentUser,
    loadCurrentUser,
    clearCurrentUser,
    clearError,
  }
})
